/* The MIT License (MIT)

	Copyright (c) 2013 Schpitt <schpitt@gmail.com>
	https://code.google.com/p/updator/

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE. */

#include "Utils.h"

#include <sstream>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <direct.h>

#include "sha2.h"

using namespace std;

namespace Updator 
{
	vector<string>& Utils::split(const string &s, char delim, vector<string> &elems) 
	{
		stringstream ss(s);
		string item;
		while(getline(ss, item, delim)) {
			elems.push_back(item);
		}
		return elems;
	}

	//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	bool Utils::str2uint(unsigned int &i, char const *s, int base)
	{
		char *end;
		long  l;
		errno = 0;
		l = strtol(s, &end, base);
		if(errno == ERANGE || *s == '\0' || *end != '\0' || l < 0) {
			return false;
		}
		i = l;
		return true;
	}

	//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	bool Utils::getHashLocalFile( const string& p_filepath, char* p_out_hash, char* p_buf, unsigned int p_buf_size ) 
	{
		SHA256_CTX	ctx256;
		FILE * file;
		size_t l, kl=0;

		SHA256_Init(&ctx256);

		file = fopen( p_filepath.c_str(), "rb" );

		if( !file )
			return false;

		while ((l = fread(p_buf,1,p_buf_size,file)) > 0) {
			kl += l;
			SHA256_Update(&ctx256, (unsigned char*)p_buf, l);
		}
		fclose (file);

		SHA256_End(&ctx256, p_buf);
		memcpy( p_out_hash, p_buf, 32 );

		return true;
	}

	//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	bool Utils::fileExists(const string& filename)
	{
		bool exist = false;
		FILE * file;
		file = fopen (filename.c_str(),"r");
		exist = file!=NULL;
		if(exist) 
			fclose(file);
		return exist;
	}

	//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	void Utils::createFolder(const string& p_file_path) 
	{
		// mkdir cant create subfolder, so we browse folder to create
		size_t slash_pos = 0;
		slash_pos = p_file_path.find("/", 0);
		while( slash_pos != string::npos ) {
			string a(p_file_path, 0, slash_pos);
			mkdir( string(p_file_path, 0, slash_pos).c_str() );
			slash_pos = p_file_path.find("/", slash_pos+1);
		}
	}

	//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	bool Utils::deleteFile(const string& p_file_path) 
	{
		return remove(p_file_path.c_str()) == 0;
	}

	//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	string Utils::urlencode(const string& s)
	{
		//RFC 3986 section 2.3 Unreserved Characters (January 2005)
		const string unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~/";

		string escaped="";
		for(size_t i=0; i<s.length(); i++) {
			if (unreserved.find_first_of(s[i]) != string::npos) {
				escaped.push_back(s[i]);
			} else {
				escaped.append("%");
				char buf[3];
				sprintf(buf, "%.2X", s[i]);
				escaped.append(buf);
			}
		}
		return escaped;
	}
}